#!/usr/bin/python


import sys, os, re, time
import shutil, signal, socket
from optparse import OptionParser

try:
  import uno
  from com.sun.star.beans import PropertyValue
except ImportError:
  print "Please install pygtk"
  raise SystemExit


LOGFILE = '/var/log/ooconvert.log'


class Log:
    def __init__(self, f):
        self.f = f
        
    def write(self, s):
        try:
            s = s.encode('CP1251')
        except:
            pass
            
        s = s.strip()
        if s != "":
            s = "[%s] %s\n" % (time.ctime(), s)
            self.f.write(s)
            self.f.flush()


def init_openoffice():
    # Init: Connect to running soffice process
    context = uno.getComponentContext()
    resolver=context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context)
    try:
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    except:
        s = "Could not connect to running openoffice."
        print s
        raise Exception, s

    smgr=ctx.ServiceManager
    desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop",ctx)
    return desktop


def convert(file, desktop, format, file_save):
    file_l=file.lower()
    
    properties=[]
    p=PropertyValue()
    p.Name="Hidden"
    p.Value=True
    properties.append(p)
    doc=desktop.loadComponentFromURL("file://%s" % file, "_blank", 0, tuple(properties));
    if not doc:
        print "Failed to open '%s'" % file
        return
    
    # Save File
    properties=[]
    p=PropertyValue()
    p.Name="Overwrite"
    p.Value=True
    properties.append(p)
    p=PropertyValue()
    p.Name="FilterName"
    p.Value=format
    properties.append(p)
    p=PropertyValue()
    p.Name="Hidden"
    p.Value=True
    try:
        doc.storeToURL("file://%s" % file_save, tuple(properties))
        print "Created %s" % file_save
    except ValueError:
        print "Failed while writing: '%s'" % file_save
    
        #?
        doc.dispose()
            
    
        
        

# DAEMON ============================================================================================

def print_help():
    print 'Usage: /etc/init.d/ooReporter.py (start|stop|restart)';
    
    
def have_param(param_name, long_name):
    i = 0;
    for i in sys.argv:
        if ((i == param_name) or (i == long_name)):
            return True
    return False;

def sigINTHandler(signum, frame):
    print "server stopping..."
    s.running = 0;
    s.server.shutdown(2);
    sys.exit(1)


            
if __name__ == "__main__" :
    parser = OptionParser(description='Convert a file from one format to another using OpenOffice')
    parser.add_option("-f","--from",action="store",dest="from_file",help="File to convert")
    parser.add_option("-a","--action",action="store",dest="format",help="Format to use")
    parser.add_option("-t","--to", action="store",dest="to_file",help="Result file")
    (opt,args) = parser.parse_args()

    if not opt.from_file:
        parser.error("set the file to convert")

    if not opt.format:
        parser.error("set the format to use")
    if not opt.to_file:
        parser.error("set the result file")

    desktop = init_openoffice()
    convert(opt.from_file, desktop,opt.format,opt.to_file)

